#coding:utf-8

import re
import types
import sys
import os
import os.path as ospath
import time

def find_all_scripts(dir_path, name):
    """ find all python scripts in the directory. If @name is not
    directory, then return itself, else return a list included
    all of scripts path:
        'dir1.dir2.dir3.dir4.file1'
        'dir1.dir2.dir3.dir4.file2'
        @dir_path: target path.
        @name: directory path. this name is not general path, it is
    written such as:
        'dir1.dir2.dir3.dir4'
        '.' # entire target directory
    path is counted begging from @dir_path.
    """
    parts = name.split('.')
    abspath = ospath.join(dir_path, *parts)
    if not ospath.isdir(abspath):
        return name
    # actually we should know if there is __init__.py existing in this
    # directory, but I think may be it is not needed, although all
    # scripts in it couldn't be imported.
    filepaths = []
    for root, dirs, files in os.walk(abspath):
        files.sort()
        filepaths += [ospath.join(root, fname) for fname in files]
        
    scripts = []
    for fpath in filepaths:
        mpath = fpath.replace(dir_path, '', 1).strip(ospath.sep)
        mpath, ext = os.path.splitext(mpath)
        dirname, fname = os.path.split(mpath)
        
        if ext == ".py" and fname != '__init__':
            mparts = mpath.split(ospath.sep)
            scripts.append('.'.join(mparts))
    return scripts

def find_same_name(filepath):
    """ Return all of files with the same name (without suffix) 
    in the same directory.
    """
    dirpath, filename = ospath.split(filepath)
    fileid, ext = ospath.splitext(filename)
    _compiler = re.compile(r'^%s\.\w+$'%fileid)
    same_files = filter(lambda fn: _compiler.match(fn), os.listdir(dirpath))
    if filename in same_files:
        same_files.remove(filename)
    return [ospath.join(dirpath, fn) for fn in same_files]

# find path from where program starts
get_abs_path = lambda path: ospath.join(os.getcwd(), path)

